package com.lh.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lh.entity.table.*;
import com.lh.mapper.*;
import com.lh.service.DsmsUserService;
import com.lh.service.ReminderService;
import com.lh.task.TimeTask;
import com.lh.utils.Answer;
import com.lh.utils.SmsGetSenderWithConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReminderServiceImpl implements ReminderService {

    @Resource
    private ReminderInfoMapper reminderInfoMapper;

    @Autowired
    private SmsGetSenderWithConfigUtil smsUtil;
    @Resource
    private DeadlineRectificationPeriodMapper deadlineRectificationPeriodMapper;
    @Resource
    private RectificationInfoMapper rectificationInfoMapper;
    @Resource
    private ReminderPersonMapper reminderPersonMapper;

    // 单位主要领导
    @Resource
    private DepartmentPersonMapper departmentPersonMapper;
    @Resource
    private DeadlineNodeMapper deadlineNodeMapper;

    @Autowired
    private DsmsUserService dsmsUserService;
    @Override
    public Answer<Object> setReminderRead(JSONObject reqJson) {
        Integer id = reqJson.getInteger("id");
        ReminderInfo reminderInfo = reminderInfoMapper.selectById(id);
        reminderInfo.setIsConfirmed(1);
        reminderInfoMapper.updateById(reminderInfo);
        return Answer.ok(1);
    }
    @Override
    public Answer<Object> queryReminderData(JSONObject reqJson) {
        try {
            Integer pageNum = reqJson.getInteger("pageNum");
            Integer pageSize = reqJson.getInteger("pageSize");
            Integer reminderType = reqJson.getInteger("reminderType");
            String reminderDepart = reqJson.getString("reminderDepart");

            if (pageNum == null || pageSize == null) {
                return Answer.error("页码和每页数量不能为空");
            }
            Page<ReminderInfo> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<ReminderInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (reminderType != null) {
                queryWrapper.eq(ReminderInfo::getReminderType, reminderType);
            }
            if (StrUtil.isNotBlank(reminderDepart)) {
                queryWrapper.eq(ReminderInfo::getReminderDepart, reminderDepart);
            }
            queryWrapper.orderByDesc(ReminderInfo::getId);
            Page<ReminderInfo> reminderInfoPage = reminderInfoMapper.selectPage(page, queryWrapper);
            return Answer.ok(reminderInfoPage);
        } catch (Exception e) {
            return Answer.error(e.getMessage());
        }
    }

    @Override
    public Answer<Object> messageWarning(JSONObject reqJson) {
        String reminderPerson = reqJson.getString("reminderPerson");
        String reminderDepart = reqJson.getString("reminderDepart");
        String reminderTitle = reqJson.getString("reminderTitle");
        String reminderType = reqJson.getString("reminderType");
        String reminderContent = reqJson.getString("reminderContent");
        String riskLevel = reqJson.getString("riskLevel");
        String deadlineId = reqJson.getString("deadlineId");
        List<ReminderPerson> reminderPeople= reminderPersonMapper.selectList(new LambdaQueryWrapper<ReminderPerson>().eq(ReminderPerson::getPersonName,reminderPerson));
        String reminderPhoneNumber = reminderPeople.get(0).getPhone();

        ReminderInfo reminderInfo = new ReminderInfo();
        if (StrUtil.isNotBlank(reminderPerson)){
            reminderInfo.setReminderPerson(reminderPerson);
        }
        if (StrUtil.isNotBlank(reminderDepart)){
            reminderInfo.setReminderPerson(reminderDepart);
        }
        if (StrUtil.isNotBlank(reminderTitle)){
            reminderInfo.setReminderPerson(reminderTitle);
        }
        if (StrUtil.isNotBlank(reminderType)){
            reminderInfo.setReminderPerson(reminderType);
        }
        if (StrUtil.isNotBlank(reminderContent)){
            reminderInfo.setReminderPerson(reminderContent);
        }
        if (StrUtil.isNotBlank(riskLevel)){
            reminderInfo.setReminderPerson(riskLevel);
        }
        if (StrUtil.isNotBlank(deadlineId)){
            reminderInfo.setReminderPerson(deadlineId);
        }
        if (StrUtil.isNotBlank(reminderPhoneNumber)){
            reminderInfo.setReminderPerson(reminderPhoneNumber);
        }

        try {
            // 调用工具类（仅传2个参数，极简使用）
            String apiResponse = smsUtil.sendSmsByGet(reminderPhoneNumber, reminderContent);
            reminderInfo.setReminderPerson(reminderPerson);
            reminderInfo.setReminderPhoneNumber(reminderPhoneNumber);
            reminderInfo.setReminderTitle("新申请审核通过");
            reminderInfo.setReminderContent(reminderContent);
            reminderInfo.setOaUser(apiResponse);
            reminderInfo.setIsSmsSent(1);
            reminderInfoMapper.insert(reminderInfo);
        } catch (IllegalArgumentException e) {
            // 处理参数错误（如手机号格式错、内容为空）
            System.err.println("参数异常：" + e.getMessage());
        } catch (Exception e) {
            // 处理网络/接口错误（如超时、响应码非200）
            System.err.println("网络/接口异常：" + e.getMessage());
        }

        return Answer.ok("发送成功");
    }

    /**
     * 只针对新案件的推送
     * @param reqJson
     * @return
     */
    @Override
    public Answer<Object> messageTitle(JSONObject reqJson) {
        Integer rectificationId = reqJson.getInteger("rectificationId");
        String title = reqJson.getString("title");
        String remindType = reqJson.getString("remindType");
        if (rectificationId!=null){
            RectificationInfo rectificationInfo =
                    rectificationInfoMapper.selectById(rectificationId);
            LambdaQueryWrapper<DeadlineNode> deadlineNodeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            deadlineNodeLambdaQueryWrapper.eq(DeadlineNode::getRectificationId, rectificationInfo.getId());
            List<DeadlineNode> deadlineNodeList = deadlineNodeMapper.selectList(deadlineNodeLambdaQueryWrapper);
            // 过滤节点
            deadlineNodeList = filiterNode(rectificationInfo, deadlineNodeList);
            deadlineNodeList.forEach(node ->{
                sendNewAddMessage(node, rectificationInfo, remindType);
            });

        }else if (StrUtil.isNotBlank(title)){
            // 找到项目 然后推送提醒;

             LambdaQueryWrapper<RectificationInfo> rectificationInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
             rectificationInfoLambdaQueryWrapper.eq(RectificationInfo::getTitle, title);
             rectificationInfoLambdaQueryWrapper.orderByDesc(RectificationInfo::getCreatedTime);
             rectificationInfoLambdaQueryWrapper.last("LIMIT 1");
             RectificationInfo rectificationInfo = rectificationInfoMapper.selectOne(rectificationInfoLambdaQueryWrapper);
             System.out.println(rectificationInfo);
             if (rectificationInfo!=null){
                 LambdaQueryWrapper<DeadlineNode> deadlineNodeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                 deadlineNodeLambdaQueryWrapper.eq(DeadlineNode::getRectificationId, rectificationInfo.getId());
                 List<DeadlineNode> deadlineNodeList = deadlineNodeMapper.selectList(deadlineNodeLambdaQueryWrapper);
                 // 过滤节点
                 deadlineNodeList = filiterNode(rectificationInfo, deadlineNodeList);
                 deadlineNodeList.forEach(node ->{
                     sendNewAddMessage(node, rectificationInfo, remindType);
                 });
             }
        }
        return Answer.ok("操作成功");
    }

    private void messageDepartment(String departmentName,String title,String content,Integer type){
        // 检查今天是否已经给该人员发送过相同项目、相同类型的提醒
        List<DsmsUser> userList = dsmsUserService.queryUserByDepartment(departmentName);
        System.out.println(userList);
        // 不要重复发
        if (CollectionUtil.isNotEmpty(userList)) {
            DsmsUser dsmsUser = userList.get(0);
            Date today = DateUtil.beginOfDay(new Date());
            // 检查今天是否已经给该人员发送过相同项目、相同类型的提醒
            LambdaQueryWrapper<ReminderInfo> lamWrap = new LambdaQueryWrapper<ReminderInfo>()
                    .eq(ReminderInfo::getReminderPhoneNumber, dsmsUser.getMobileNo())
                    .eq(ReminderInfo::getReminderContent, content)
                    .eq(ReminderInfo::getReminderTitle, title)
                    .ge(ReminderInfo::getCreatedTime, today); // 只检查今天的记录
            List<ReminderInfo> existingReminders = reminderInfoMapper.selectList(lamWrap);
            if (CollectionUtil.isEmpty(existingReminders)) {
                System.out.println(existingReminders);
                ReminderInfo reminderInfo = new ReminderInfo();
                reminderInfo.setReminderDepart(dsmsUser.getDepartment());
                reminderInfo.setReminderPerson(dsmsUser.getUserName());
                reminderInfo.setReminderPhoneNumber(dsmsUser.getMobileNo());
                reminderInfo.setReminderContent(content);
                reminderInfo.setReminderTitle(title);
                reminderInfo.setReminderTime(new Date());
                reminderInfo.setReminderType(0);
                reminderInfo.setCreatedTime(new Date());
                reminderInfo.setType(type);
                String apiResponse = null;
                try {
                    apiResponse = smsUtil.sendSmsByGet(dsmsUser.getMobileNo(), content);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                reminderInfo.setOaUser(apiResponse);
                reminderInfo.setIsSmsSent(0);
                reminderInfoMapper.insert(reminderInfo);
                System.out.println(reminderInfo);
            }
        }
    }


    private void messagePerson(String person,String title,String content,Integer type){
        person = person.trim();
        person = person.replace(" ","");
        List<ReminderPerson> reminderPeople = reminderPersonMapper.selectList(
                new LambdaQueryWrapper<ReminderPerson>().eq(ReminderPerson::getPersonName, person));
        String targetPhone = null;
        String targetName = person;
        String department = null;
        if (CollectionUtil.isNotEmpty(reminderPeople) &&
                StringUtils.isNotBlank(reminderPeople.get(0).getPhone())) {
            targetPhone = reminderPeople.get(0).getPhone();
            targetName = reminderPeople.get(0).getPersonName();
            department = reminderPeople.get(0).getUnitName();
        }
        // 如果找不到手机号，跳过该人员
        if (StrUtil.isBlank(targetPhone)) {
            log.warn("未找到人员 {} 的手机号，跳过发送短信", person);
        }
        // 获取今天的起始时间（00:00:00）
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        // 获取今天的结束时间（23:59:59.999）
        LocalDateTime todayEnd = LocalDate.now().atTime(23, 59, 59, 999);
        // 转换为Date类型（如果需要，根据实际序列化方式调整）
        Date startDate = Date.from(todayStart.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(todayEnd.atZone(ZoneId.systemDefault()).toInstant());
        // 检查今天是否已经给该人员发送过相同项目、相同类型的提醒
        LambdaQueryWrapper<ReminderInfo> userLamWrap = new LambdaQueryWrapper<ReminderInfo>()
                .eq(ReminderInfo::getReminderPhoneNumber, targetPhone)
                .ge(ReminderInfo::getCreatedTime, startDate)  // 大于等于今天0点
                .le(ReminderInfo::getCreatedTime, endDate)   // 小于等于今天23:59:59
                .eq(ReminderInfo::getReminderContent, content);
        List<ReminderInfo> list = reminderInfoMapper.selectList(userLamWrap);
        if (list!=null && list.size()>=1){
            log.warn("已发送给，跳过发送短信", person);
            return;
        }
        ReminderInfo reminderInfo = new ReminderInfo();
        reminderInfo.setReminderDepart(department);
        reminderInfo.setReminderPerson(targetName);
        reminderInfo.setReminderPhoneNumber(targetPhone);
        reminderInfo.setReminderContent(content);
        reminderInfo.setReminderTitle(title);
        reminderInfo.setReminderTime(new Date());
        reminderInfo.setReminderType(0);
        reminderInfo.setCreatedTime(new Date());
        reminderInfo.setType(type);
        String apiResponse = null;
//        try {
//            apiResponse = smsUtil.sendSmsByGet(targetPhone, content);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        reminderInfo.setReminderPerson(targetName);
        reminderInfo.setReminderPhoneNumber(targetPhone);
        reminderInfo.setOaUser(apiResponse);
        reminderInfo.setIsSmsSent(0);
        reminderInfoMapper.insert(reminderInfo);
    }

    @Override
    public Answer<Object> messageXfNew(JSONObject reqJson){
        List<Integer> recIdList = Arrays.asList(1440,
                1532);
        recIdList.forEach(item->{
            RectificationInfo rectificationInfo =
                    rectificationInfoMapper.selectById(item);
            LambdaQueryWrapper<DeadlineNode> deadlineNodeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            deadlineNodeLambdaQueryWrapper.eq(DeadlineNode::getRectificationId, rectificationInfo.getId());
            List<DeadlineNode> deadlineNodeList = deadlineNodeMapper.selectList(deadlineNodeLambdaQueryWrapper);
            // 过滤节点
            deadlineNodeList = filiterNode(rectificationInfo, deadlineNodeList);
            deadlineNodeList.forEach(node ->{
                sendNewAddMessage(node, rectificationInfo, "新申请审核通过");
            });
        });

        return Answer.ok("操作成功");
    }

    @Override
    public Answer<Object> messageProjectStatus(JSONObject reqJson) {
        // 新申请待审核
        // 新申请审核不通过
        // 新申请审核通过
        // 更新进度待审核
        // 更新进度审核通过
        // 更新进度审核不通过
        // 修改申请待审核
        // 修改申请审核不通过
        // 修改申请审核通过
        // 退出申请待审核
        // 退出申请审核不通过
        // 退出申请审核通过
        // 销号申请待审核
        // 销号申请审核不通过
        // 销号申请审核通过
        String status = reqJson.getString("status");
        String title = reqJson.getString("title");
        if (StrUtil.isEmptyIfStr(status)){
            return Answer.error("操作失败");
        }
        if (status.equals("新申请待审核")){
            // 给approvalId 推送 暂时不推送
            String checkRemark = reqJson.getString("checkRemark"); // 督查室
            String creatorUnit = reqJson.getString("creatorUnit"); // 督查室
            if (StrUtil.isNotBlank(checkRemark)){
                if (checkRemark.equals("市委督查室")){
                    String msgContent = creatorUnit+"新提交了重点工作"+title+"，请及时审核";
                    messageDepartment("市委督查室","新申请待审核",msgContent,1);
                }else{
                    String msgContent = creatorUnit+"新提交了重点工作"+title+"，请及时审核";
                    messageDepartment("市政府督查室","新申请待审核",msgContent,1);
                }
            }
        }else if (status.equals("新申请审核不通过")){
            // 发起单位操作人员
            String creatorUnit = reqJson.getString("creatorUnit");
            String msgContent = "您提交的重点工作"+title+"审核不通过，请及时处理。";
            messageDepartment(creatorUnit,"新申请审核不通过",msgContent,2);
        }else if (status.equals("新申请审核通过")){
//            发起单位操作人员
//            牵头单位主要领导（市直）
//            牵头单位责任人
//            牵头单位操作人员
//            责任单位主要领导（市直）
//            责任单位责任人
//            责任单位操作人员
            LambdaQueryWrapper<RectificationInfo> rectificationInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            rectificationInfoLambdaQueryWrapper.eq(RectificationInfo::getTitle, title);
            rectificationInfoLambdaQueryWrapper.orderByDesc(RectificationInfo::getCreatedTime);
            rectificationInfoLambdaQueryWrapper.last("LIMIT 1");
            RectificationInfo rectificationInfo = rectificationInfoMapper.selectOne(rectificationInfoLambdaQueryWrapper);
            System.out.println(rectificationInfo);
            if (rectificationInfo!=null){
                LambdaQueryWrapper<DeadlineNode> deadlineNodeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                deadlineNodeLambdaQueryWrapper.eq(DeadlineNode::getRectificationId, rectificationInfo.getId());
                List<DeadlineNode> deadlineNodeList = deadlineNodeMapper.selectList(deadlineNodeLambdaQueryWrapper);
                // 过滤节点
                deadlineNodeList = filiterNode(rectificationInfo, deadlineNodeList);
                deadlineNodeList.forEach(node ->{
                    sendNewAddMessage(node, rectificationInfo, "新申请审核通过");
                });
            }

        }else if (status.equals("更新进度待审核")){
//            发起单位操作人员
            String creatorUnit = reqJson.getString("creatorUnit");
            String leaderDepartment = reqJson.getString("leaderDepartment");
            if (StrUtil.isEmptyIfStr(leaderDepartment)){
                leaderDepartment = "";
            }
            if (!creatorUnit.equals(leaderDepartment)){
                String msgContent = "牵头单位"+leaderDepartment+"申请更新《"+title+"》工作进度，请及时登录平台审核。";
                messageDepartment(creatorUnit,"更新进度待审核",msgContent,4);
            }
        }else if (status.equals("更新进度审核通过")){
//            牵头单位操作人员
//            责任单位责任人【有修改进度的相关责任人】
//            责任单位操作人员
            String leaderDepartment = reqJson.getString("leaderDepartment"); // 牵头单位
            String msgContent1 = "您提交的重点工作《"+title+"》进度更新申请已通过，请关注。";
            messageDepartment(leaderDepartment,"更新进度审核通过",msgContent1,5);

            Integer nodeId = reqJson.getInteger("nodeId");
            if (nodeId!=null){
                DeadlineNode deadNode = deadlineNodeMapper.selectById(nodeId);
                String nodeDepartment = deadNode.getDepartmentName(); // 环节单位
                String nodePerson = deadNode.getDescription(); // 责任人
                // 1.牵头单位操作人员 您提交的重点工作《XX（项目标题）》进度更新申请已通过/不通过，请关注。
                // 2.责任单位操作人员 你单位提请修改重点工作《XX（项目标题）》进度更新申请已通过/不通过，请关注。。
                if (StrUtil.isNotBlank(nodeDepartment)){
                    if (!DISTRICTS.contains(leaderDepartment)){
                        String deptName = nodeDepartment;
                        if (deptName.contains("发改")){
                            deptName = "市发改委";
                        }else if (deptName.contains("资建")){
                            deptName = "市资建局";
                        }else if (deptName.contains("林业")){
                            deptName = "市林业局";
                        }else if (deptName.contains("财政")){
                            deptName = "市财政局";
                        }else if (deptName.contains("生态")){
                            deptName = "市生态环境局";
                        }else if (deptName.contains("应急")){
                            deptName = "市应急管理局";
                        }else if (deptName.contains("自规")){
                            deptName = "市自然资源规划局";
                        }else if (deptName.contains("住建")){
                            deptName = "市住新局";
                        }
                        String msgContent2 = "你单位提请修改重点工作《"+title+"》进度更新申请已通过，请关注。";
                        messageDepartment(deptName,"更新进度审核通过",msgContent2,5);
                    }
                }
                //责任单位责任人
                if (StrUtil.isNotBlank(nodePerson)){
                    String msgContent3 = "你提请修改重点工作《"+title+"》进度更新申请已通过，请关注。";
                    messagePerson(nodePerson,"更新进度审核通过",msgContent3,5);
                }
            }

        }else if (status.equals("更新进度审核不通过")){
            String leaderDepartment = reqJson.getString("leaderDepartment"); // 牵头单位
            // 1.牵头单位操作人员 您提交的重点工作《XX（项目标题）》进度更新申请已通过/不通过，请关注。
            String msgContent1 = "您提交的重点工作《"+title+"》进度更新申请不通过，请关注。";
            messageDepartment(leaderDepartment,"更新进度审核不通过",msgContent1,5);
            // 获取责任人库,看这个环节的责任人是不是是发改的.
            Integer nodeId = reqJson.getInteger("nodeId");
            if (nodeId!=null){
                DeadlineNode deadNode = deadlineNodeMapper.selectById(nodeId);
                String nodeDepartment = deadNode.getDepartmentName(); // 环节单位
                String nodePerson = deadNode.getDescription(); // 责任人
                // 1.牵头单位操作人员 您提交的重点工作《XX（项目标题）》进度更新申请已通过/不通过，请关注。
                // 2.责任单位操作人员 你单位提请修改重点工作《XX（项目标题）》进度更新申请已通过/不通过，请关注。。
                if (StrUtil.isNotBlank(nodeDepartment)){
                    if (!DISTRICTS.contains(leaderDepartment)){
                        String deptName = nodeDepartment;
                        if (deptName.contains("发改")){
                            deptName = "市发改委";
                        }else if (deptName.contains("资建")){
                            deptName = "市资建局";
                        }else if (deptName.contains("林业")){
                            deptName = "市林业局";
                        }else if (deptName.contains("财政")){
                            deptName = "市财政局";
                        }else if (deptName.contains("生态")){
                            deptName = "市生态环境局";
                        }else if (deptName.contains("应急")){
                            deptName = "市应急管理局";
                        }else if (deptName.contains("自规")){
                            deptName = "市自然资源规划局";
                        }else if (deptName.contains("住建")){
                            deptName = "市住新局";
                        }
                        String msgContent2 = "你单位提请修改重点工作《"+title+"》进度更新申请不通过，请关注。";
                        messageDepartment(deptName,"更新进度审核不通过",msgContent2,5);
                    }
                }
                //责任单位责任人
                if (StrUtil.isNotBlank(nodePerson)){
                    String msgContent3 = "你提请修改重点工作《"+title+"》进度更新申请不通过，请关注。";
                    messagePerson(nodePerson,"更新进度审核不通过",msgContent3,5);
                }
            }
        }else if (status.equals("修改申请待审核")){
            String checkRemark = reqJson.getString("checkRemark"); // 督查室
            String creatorUnit = reqJson.getString("creatorUnit"); // 督查室
            if (StrUtil.isNotBlank(checkRemark)){
                if (checkRemark.equals("市委督查室")){
                    String msgContent = creatorUnit+"申请修改重点工作"+title+"，请及时审核";
                    messageDepartment("市委督查室","修改申请待审核",msgContent,6);
                }else{
                    String msgContent = creatorUnit+"申请修改重点工作"+title+"，请及时审核";
                    messageDepartment("市政府督查室","修改申请待审核",msgContent,6);
                }
            }
        }else if (status.equals("修改申请审核不通过")){
            //您申请修改重点工作《XX（项目标题）》信息审核已通过/未通过，请关注。
            String creatorUnit = reqJson.getString("creatorUnit"); // 督查室
            String msgContent = "您申请的修改重点工作"+title+"信息审核未通过，请关注。";
            messageDepartment(creatorUnit,"修改申请审核不通过",msgContent,7);
        }else if (status.equals("修改申请审核通过")){
            //您申请修改重点工作《XX（项目标题）》信息审核已通过/未通过，请关注。
            String creatorUnit = reqJson.getString("creatorUnit"); // 督查室
            String msgContent = "您申请修改的重点工作"+title+"信息审核已通过，请关注。";
            messageDepartment(creatorUnit,"修改申请审核通过",msgContent,8);
        }else if (status.equals("申请销号待审核")){
            String checkRemark = reqJson.getString("checkRemark"); // 督查室
            String creatorUnit = reqJson.getString("creatorUnit"); // 督查室
            if (StrUtil.isNotBlank(checkRemark)){
                if (checkRemark.equals("市委督查室")){
                    String msgContent = creatorUnit+"申请销号重点工作"+title+"，请及时审核";
                    messageDepartment("市委督查室","申请销号待审核",msgContent,9);
                }else{
                    String msgContent = creatorUnit+"申请销号重点工作"+title+"，请及时审核";
                    messageDepartment("市政府督查室","申请销号待审核",msgContent,9);
                }
            }
        }else if (status.equals("销号申请审核不通过")){
            //您申请修改重点工作《XX（项目标题）》信息审核已通过/未通过，请关注。
            String creatorUnit = reqJson.getString("creatorUnit"); // 督查室
            String msgContent = "您申请销号的重点工作"+title+"信息审核未通过，请关注。";
            messageDepartment(creatorUnit,"销号申请审核不通过",msgContent,10);
        }else if (status.equals("销号申请审核通过")){
            //您申请修改重点工作《XX（项目标题）》信息审核已通过/未通过，请关注。
            String creatorUnit = reqJson.getString("creatorUnit"); // 督查室
            String msgContent = "您申请销号的重点工作"+title+"信息审核已通过，请关注。";
            messageDepartment(creatorUnit,"销号申请审核已通过",msgContent,11);
        }else if (status.equals("申请退出待审核")){
            String checkRemark = reqJson.getString("checkRemark"); // 督查室
            String creatorUnit = reqJson.getString("creatorUnit"); // 督查室
            if (StrUtil.isNotBlank(checkRemark)){
                if (checkRemark.equals("市委督查室")){
                    String msgContent = creatorUnit+"申请退出重点工作"+title+"，请及时审核";
                    messageDepartment("市委督查室","申请退出待审核",msgContent,9);
                }else{
                    String msgContent = creatorUnit+"申请销号重点工作"+title+"，请及时审核";
                    messageDepartment("市政府督查室","申请退出待审核",msgContent,9);
                }
            }
        }else if (status.equals("退出申请审核不通过")){
            //您申请修改重点工作《XX（项目标题）》信息审核已通过/未通过，请关注。
            String creatorUnit = reqJson.getString("creatorUnit"); // 督查室
            String msgContent = "您申请退出的重点工作"+title+"信息审核未通过，请关注。";
            messageDepartment(creatorUnit,"退出申请审核不通过",msgContent,10);
        }else if (status.equals("退出申请审核通过")){
            //您申请修改重点工作《XX（项目标题）》信息审核已通过/未通过，请关注。
            String creatorUnit = reqJson.getString("creatorUnit"); // 督查室
            String msgContent = "您申请退出的重点工作"+title+"信息审核已通过，请关注。";
            messageDepartment(creatorUnit,"退出申请审核通过",msgContent,11);
        }
        return Answer.ok("操作成功");
    }

    @Override
    public Answer<Object> getCountByDate(JSONObject reqJson) {
        String date = reqJson.getString("date");
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;

        // 去掉日期验证：直接尝试转换，转换失败则不限制日期（查询所有）
        if (date != null && !date.trim().isEmpty()) {
            try {
                LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE);
                startTime = localDate.atStartOfDay();
                endTime = localDate.atTime(LocalTime.MAX);
            } catch (Exception e) {
                // 日期格式错误时，不限制日期范围（查询所有type=2的记录）
                startTime = null;
                endTime = null;
            }
        }

        // 红灯类型: 24
        // 二次红灯: 85 86,87,88
        // 黄灯类型: 23
        // 新增: 0
        ArrayList<Integer> allTypeList = new ArrayList<>();
        allTypeList.add(0);
        allTypeList.add(23);
        allTypeList.add(24);
        allTypeList.add(85);
        allTypeList.add(86);
        allTypeList.add(87);
        allTypeList.add(88);
        // 2. 查询数据
        // 2.1 查询符合条件的ReminderInfo（type=2 + 日期范围，日期错误则查所有）
        List<ReminderInfo> reminderInfoList = reminderInfoMapper.selectList(
                new LambdaQueryWrapper<ReminderInfo>()
//                        .eq(ReminderInfo::getType, 2)
                        .isNotNull(ReminderInfo::getReminderDepart)
                        .in(ReminderInfo::getType,allTypeList)
                        .ge(startTime != null, ReminderInfo::getCreatedTime, startTime)
                        .le(endTime != null, ReminderInfo::getCreatedTime, endTime)
        );
        reminderInfoList = reminderInfoList == null ? new ArrayList<>() : reminderInfoList;
        // 核心：根据 type + deadlineId 去重（保留首次出现的元素）
        reminderInfoList = reminderInfoList.stream()
                // 收集到 LinkedHashMap，键为 type+deadlineId（兼容null），值为元素本身
                .collect(Collectors.toMap(
                        // 生成唯一键：type + "_" + deadlineId（处理null避免空指针）
                        info -> {
                            String typeStr = info.getType() == null ? "null" : info.getType().toString();
                            String deadlineIdStr = info.getDeadlineId() == null ? "null" : info.getDeadlineId().toString();
                            return typeStr + "_" + deadlineIdStr;
                        },
                        // 值为元素本身
                        info -> info,
                        // 重复时保留第一个元素
                        (existing, replacement) -> existing,
                        // 使用LinkedHashMap保证顺序
                        LinkedHashMap::new
                ))
                // 提取去重后的value集合，转为List
                .values()
                .stream()
                .collect(Collectors.toList());
        // 2.2 构建deadlineId->warnLevel映射
        // 3. 按reminderDepart分组（空部门归为"未知部门"）
        Map<String, List<ReminderInfo>> deptReminderMap = reminderInfoList.stream()
                .collect(Collectors.groupingBy(
                        reminder -> {
                            String dept = reminder.getReminderDepart();
                            return (dept == null || dept.trim().isEmpty()) ? "未知部门" : dept.trim();
                        },
                        Collectors.toList()
                ));

        // 4. 统计有数据的部门，并按DISTRICTS顺序排序
        List<Map<String, Object>> deptStatList = new ArrayList<>();

        // 4.1 先处理DISTRICTS列表中的部门（按顺序，仅保留有数据的）
        for (String district : DISTRICTS) {
            List<ReminderInfo> deptReminders = deptReminderMap.get(district);
            if (deptReminders == null || deptReminders.isEmpty()) {
                continue; // 无数据，跳过不显示
            }

            // 统计当前部门数据
            int deptTotal = 0;
            int deptRed = 0; // warnLevel=2
            int deptYellow = 0; // warnLevel=1
            for (ReminderInfo reminder : deptReminders) {
                if (reminder.getType() == 23){
                    deptYellow++;
                }else if (reminder.getType() > 23){
                    deptRed++;
                }else{
                    deptTotal++;
                }
//                String warnLevel = deadlineWarnLevelMap.get(deadlineId);
//                if ("1".equals(warnLevel)) {
//                    deptYellow++;
//                } else if ("2".equals(warnLevel)) {
//                    deptRed++;
//                }
            }

            // 封装有数据的部门统计结果
            Map<String, Object> deptStat = new HashMap<>();
            deptStat.put("reminderDepart", district);
            deptStat.put("total", deptTotal);
            deptStat.put("red", deptRed);
            deptStat.put("yellow", deptYellow);
            deptStatList.add(deptStat);

            // 移除已处理的部门，避免重复
            deptReminderMap.remove(district);
        }

        // 4.2 处理剩余未在DISTRICTS中的有数据部门（如"未知部门"，追加到末尾）
        for (Map.Entry<String, List<ReminderInfo>> entry : deptReminderMap.entrySet()) {
            String dept = entry.getKey();
            List<ReminderInfo> deptReminders = entry.getValue();
            if (deptReminders.isEmpty()) {
                continue; // 无数据，跳过
            }

            // 统计数据
            int deptTotal = 0;
            int deptRed = 0;
            int deptYellow = 0;
            for (ReminderInfo reminder : deptReminders) {
                if (reminder.getType() == 23){
                    deptYellow++;
                }else if (reminder.getType() > 23){
                    deptRed++;
                }else{
                    deptTotal++;
                }
            }
            if (dept.contains("发改")) {
                dept="市发改委";
            } else if (dept.contains("资建")) {
                dept="市资建局";
            } else if (dept.contains("林业")) {
                dept="市林业局";
            } else if (dept.contains("财政")) {
                dept="市财政局";
            } else if (dept.contains("生态")) {
                dept="市生态环境局";
            } else if (dept.contains("应急")) {
                dept="市应急管理局";
            } else if (dept.contains("自规")) {
                dept="市自然资源规划局";
            } else if (dept.contains("住建")) {
                dept="市住新局";
            }
            // 封装结果
            Map<String, Object> deptStat = new HashMap<>();
            deptStat.put("reminderDepart", dept);
            deptStat.put("total", deptTotal); //新上线
            deptStat.put("red", deptRed); //红灯
            deptStat.put("yellow", deptYellow); //黄灯
            deptStatList.add(deptStat);
        }


        // 5. 封装返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("deptStatList", deptStatList);
        resultMap.put("queryDate", date); // 回显传入的日期（无论格式是否正确）

        return Answer.ok(resultMap);
    }

    // 区划列表
    private static final List<String> DISTRICTS = Arrays.asList(
            "黄州区", "团风县", "红安县", "麻城市",
            "罗田县", "英山县", "浠水县", "蕲春县",
            "武穴市", "黄梅县", "龙感湖管理区", "白莲河示范区", "黄冈高新区", "市临空经济区"
    );

    public void sendNewAddMessage(DeadlineNode deadlineNode, RectificationInfo rectificationInfo,
                                  String remindType) {

        String messageTitleType = "重点工作";

        if (rectificationInfo.getProjectChildType().equals("信访积案化解")){
            messageTitleType = "信访积案";
        }
        // 收集所有需要通知的人员
        // 推送的内容;
        // 推送的单位;
        Map<String,ReminderInfo> allResponsiblePeople = new HashMap<>();
        //责任单位主要领导（市直）
        //责任单位责任人
        //责任单位操作人员
        // 1. 环节责任人发
        if (StrUtil.isNotBlank(deadlineNode.getDescription())) {
            String[] nodeResponsiblePeople = deadlineNode.getDescription().split("[,/.、]");
            for (String person : nodeResponsiblePeople) {
                ReminderInfo reminderInfo = new ReminderInfo();
                reminderInfo.setReminderPerson(person.trim());
                reminderInfo.setReminderDepart(deadlineNode.getDepartmentName());
                //责任单位责任人 环节的
                if (remindType.equals("新申请审核通过")){
                    String title = messageTitleType+rectificationInfo.getTitle()+"已上线，您有工作任务，请关注。";
                    System.out.println(title);
                    reminderInfo.setReminderTitle("新申请审核通过");
                    reminderInfo.setReminderContent(title);
                    reminderInfo.setType(0);
                }
                allResponsiblePeople.put(person.trim(),reminderInfo);
            }
        }

        // 这个项目不是市直部门的项目
        if (DISTRICTS.contains(rectificationInfo.getDepartmentName())){
            // 给操作人员发
            // 下面给项目的部门的操作人员发代替了
        }else{
            // 环节的操作人员发
            // 市直的给环节的责任单位的操作人员发 -- 市直的
            // 环节的
            // 市直责任单位的环节
            //给责任单位主要领导发
            String deptName = deadlineNode.getDepartmentName();
            if (StrUtil.isNotBlank(deptName)){
                if (deptName.contains("发改")){
                    deptName = "市发改委";
                }else if (deptName.contains("资建")){
                    deptName = "市资建局";
                }else if (deptName.contains("林业")){
                    deptName = "市林业局";
                }else if (deptName.contains("财政")){
                    deptName = "市财政局";
                }else if (deptName.contains("生态")){
                    deptName = "市生态环境局";
                }else if (deptName.contains("应急")){
                    deptName = "市应急管理局";
                }else if (deptName.contains("自规")){
                    deptName = "市自然资源规划局";
                }else if (deptName.contains("住建")){
                    deptName = "市住新局";
                }
                LambdaQueryWrapper<DepartmentPerson> lamWrap = new LambdaQueryWrapper<DepartmentPerson>()
                        .eq(DepartmentPerson::getUnitName, deptName);
                List<DepartmentPerson> departmentPersonList = departmentPersonMapper.selectList(lamWrap);
                if (CollectionUtil.isNotEmpty(departmentPersonList)) {
                    //给责任单位主要领导发
                    for (DepartmentPerson departmentPerson : departmentPersonList) {
                        System.out.println(departmentPerson);
                        ReminderInfo reminderInfo = new ReminderInfo();
                        reminderInfo.setReminderDepart(deptName);
                        reminderInfo.setReminderPerson(departmentPerson.getPersonName());
                        if (remindType.equals("新申请审核通过")){
                            String title = messageTitleType+rectificationInfo.getTitle()+"已上线，您单位有工作任务，请关注。";
                            reminderInfo.setReminderContent(title);
                            reminderInfo.setReminderTitle("新申请审核通过");
                            reminderInfo.setType(0);
                        }
                        reminderInfo.setReminderPhoneNumber(departmentPerson.getPhone());
                        allResponsiblePeople.put(departmentPerson.getPersonName(),reminderInfo);
                    }
                }
                List<DsmsUser> userList = dsmsUserService.queryUserByDepartment(deptName);

                if (CollectionUtil.isNotEmpty(userList)) {
                    DsmsUser dsmsUser = userList.get(0);
                    ReminderInfo reminderInfo = new ReminderInfo();
                    reminderInfo.setReminderDepart(deadlineNode.getDepartmentName());
                    reminderInfo.setReminderPerson(dsmsUser.getUserName());
                    if (remindType.equals("新申请审核通过")){
                        String title = messageTitleType+rectificationInfo.getTitle()+"已上线，您单位有工作任务，请关注。";
                        reminderInfo.setReminderContent(title);
                        reminderInfo.setReminderTitle("新申请审核通过");
                        reminderInfo.setType(0);
                    }
                    reminderInfo.setReminderPhoneNumber(dsmsUser.getMobileNo());
                    allResponsiblePeople.put(dsmsUser.getUserName(),reminderInfo);
                }

            }
        }
        // 给牵头单位的责任人发
        // 2. 添加RectificationInfo的 牵头单位责任人
        if (StrUtil.isNotBlank(rectificationInfo.getPersonLiaible())) {
            String[] rectificationResponsiblePeople = rectificationInfo.getPersonLiaible().split("[,/.、]");
            for (String person : rectificationResponsiblePeople) {
                ReminderInfo reminderInfo = new ReminderInfo();
                reminderInfo.setReminderPerson(person.trim());
                reminderInfo.setReminderDepart(rectificationInfo.getDepartmentName());
                //责任单位责任人 环节的
                if (remindType.equals("新申请审核通过")){
                    String zerenTitle = "您单位牵头的";
                    if (rectificationInfo.getProjectChildType().equals("信访积案化解")){
                        zerenTitle = "您包保的";
                    }
                    String title = zerenTitle+messageTitleType+rectificationInfo.getTitle()+"已上线，请关注。";
                    reminderInfo.setReminderContent(title);
                    reminderInfo.setReminderTitle("新申请审核通过");
                    reminderInfo.setType(0);
                }
                allResponsiblePeople.put(person.trim(),reminderInfo);
            }
        }

        String leadUnit = rectificationInfo.getDepartmentName();
        String[] leadDepartment = leadUnit.split("[,/.、]");
        for (String leadDept : leadDepartment) {
            //  给牵头单位操作人员发
            List<DsmsUser> userList = dsmsUserService.queryUserByDepartment(leadDept);
            if (CollectionUtil.isNotEmpty(userList)) {
                if (DISTRICTS.contains(leadDept)){
                    List<DsmsUser> filteredList = userList.stream()
                            .filter(user -> {
                                String job = user.getJob();
                                return "市委督查室".equals(job) || "政府督查室".equals(job) || "操作人员".equals(job);
                            }).collect(Collectors.toList());
                    if (filteredList == null || filteredList.size() == 0){
                        filteredList =new ArrayList<>();
                        filteredList.add(userList.get(0));
                    }
                    String finalMessageTitleType = messageTitleType;
                    filteredList.forEach(dsmsUser ->{
                        ReminderInfo reminderInfo = new ReminderInfo();
                        reminderInfo.setReminderDepart(dsmsUser.getDepartment());
                        reminderInfo.setReminderPerson(dsmsUser.getUserName());
                        if (remindType.equals("新申请审核通过")){
                            String title = "您单位牵头的"+ finalMessageTitleType +
                                    rectificationInfo.getTitle()+"已上线，请关注。";
                            reminderInfo.setReminderContent(title);
                            reminderInfo.setReminderTitle("新申请审核通过");
                            reminderInfo.setType(0);
                        }
                        reminderInfo.setReminderPhoneNumber(dsmsUser.getMobileNo());
                        allResponsiblePeople.put(dsmsUser.getUserName(),reminderInfo);
                    });
                }else{
                    DsmsUser dsmsUser = userList.get(0);
                    ReminderInfo reminderInfo = new ReminderInfo();
                    reminderInfo.setReminderDepart(dsmsUser.getDepartment());
                    reminderInfo.setReminderPerson(dsmsUser.getUserName());
                    if (remindType.equals("新申请审核通过")){
                        String title = "您单位牵头的"+messageTitleType+rectificationInfo.getTitle()+"已上线，请关注。";
                        reminderInfo.setReminderContent(title);
                        reminderInfo.setReminderTitle("新申请审核通过");
                        reminderInfo.setType(0);
                    }
                    reminderInfo.setReminderPhoneNumber(dsmsUser.getMobileNo());
                    allResponsiblePeople.put(dsmsUser.getUserName(),reminderInfo);
                }
            }
            //给牵头单位的主要领导发
            LambdaQueryWrapper<DepartmentPerson> lamWrap = new LambdaQueryWrapper<DepartmentPerson>()
                    .eq(DepartmentPerson::getUnitName, leadDept);
            List<DepartmentPerson> departmentPersonList = departmentPersonMapper.selectList(lamWrap);
            if (CollectionUtil.isNotEmpty(departmentPersonList)) {
                for (DepartmentPerson departmentPerson : departmentPersonList) {
                    ReminderInfo reminderInfo = new ReminderInfo();
                    reminderInfo.setReminderPerson(departmentPerson.getPersonName());
                    if (remindType.equals("新申请审核通过")){
                        String title = "您单位牵头的"+messageTitleType+rectificationInfo.getTitle()+"已上线，请关注。";
                        reminderInfo.setReminderContent(title);
                        reminderInfo.setReminderTitle("新申请审核通过");
                        reminderInfo.setType(23);
                    }
                    reminderInfo.setReminderPhoneNumber(departmentPerson.getPhone());
                    allResponsiblePeople.put(departmentPerson.getPersonName(),reminderInfo);
                }
            }
        }
        // 获取今天的日期（用于按天去重）
        Date today = DateUtil.beginOfDay(new Date());
        for(String key : allResponsiblePeople.keySet()) {
            ReminderInfo reminderInfo = allResponsiblePeople.get(key);
            String targetPhone = reminderInfo.getReminderPhoneNumber();
            String responsiblePerson = key;
            String smsContent = reminderInfo.getReminderContent();
            System.out.println(smsContent);
            if (StrUtil.isBlank(targetPhone)){
                List<ReminderPerson> reminderPeople = reminderPersonMapper.selectList(
                        new LambdaQueryWrapper<ReminderPerson>().eq(ReminderPerson::getPersonName, responsiblePerson));
                if (CollectionUtil.isNotEmpty(reminderPeople) && StringUtils.isNotBlank(reminderPeople.get(0).getPhone())) {
                    targetPhone = reminderPeople.get(0).getPhone();
                }
                // 👇 若targetPhone为null，直接跳过发送
                if (StrUtil.isBlank(targetPhone)) {
                    log.warn("未找到人员 {} 的手机号，跳过发送短信", responsiblePerson);
                    reminderInfo.setReminderPerson(responsiblePerson);
                    reminderInfo.setReminderContent("未找到人员 "+responsiblePerson+" 的手机号，跳过发送短信");
                    reminderInfo.setIsSmsSent(4);
                    reminderInfoMapper.insert(reminderInfo);
                    continue;
                }
            }
            reminderInfo.setReminderPerson(responsiblePerson);
            reminderInfo.setReminderPhoneNumber(targetPhone);
            reminderInfo.setDeadlineId(deadlineNode.getId());
            reminderInfo.setRectificationLinkId(deadlineNode.getRectificationId());
            reminderInfo.setCreatedTime(new Date());
            reminderInfo.setType(0);
            reminderInfo.setRiskLevel("0");
            if (StrUtil.isEmptyIfStr(targetPhone)){
                continue;
            }
            try {
                // 检查今天是否已经给该人员发送过相同项目、相同类型的提醒
                LambdaQueryWrapper<ReminderInfo> lamWrap = new LambdaQueryWrapper<ReminderInfo>()
                        .eq(ReminderInfo::getReminderPhoneNumber, targetPhone)
                        .eq(ReminderInfo::getRectificationLinkId, deadlineNode.getRectificationId())
                        .eq(ReminderInfo::getType, 0)
                        .ge(ReminderInfo::getCreatedTime, today); // 只检查今天的记录
                List<ReminderInfo> existingReminders = reminderInfoMapper.selectList(lamWrap);
                if (CollectionUtil.isEmpty(existingReminders)) {
                    // 发送短信（这里注释掉了实际的短信发送代码）
                    String apiResponse = smsUtil.sendSmsByGet(targetPhone, smsContent);
                    reminderInfo.setReminderPerson(responsiblePerson);
                    reminderInfo.setReminderPhoneNumber(targetPhone);
                    reminderInfo.setReminderTitle("新申请审核通过");
                    reminderInfo.setReminderContent(smsContent);
                    reminderInfo.setOaUser(apiResponse);
                    reminderInfo.setIsSmsSent(1);
                    reminderInfoMapper.insert(reminderInfo);
                    log.info("已发送提醒给 {}：{}", responsiblePerson, smsContent);
                } else {
                    log.info("今天已经给 {} 发送过相同项目、相同类型的提醒，跳过", responsiblePerson);
                }
            } catch (Exception e) {
                log.error("发送短信异常：{}", e.getMessage(), e);
            }
        }
    }

    private boolean isProjectLeader(String leader, RectificationInfo rectificationInfo) {
        if (StrUtil.isBlank(rectificationInfo.getPersonLiaible())) {
            return false;
        }
        String[] responsiblePersons = rectificationInfo.getLeadLeader().split("[,/.、]");
        for (String person : responsiblePersons) {
            if (person.trim().equals(leader)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 手动推送报警
     * @param reqJson
     * @return
     */
    @Override
    public Answer<Object> messageRemindUser(JSONObject reqJson) {
        String reminderTitle = reqJson.getString("reminderTitle");
        String reminderDepartment = reqJson.getString("reminderDepartment");
        String reminderContent = reqJson.getString("reminderContent");
        Integer type = reqJson.getInteger("type");
        Integer reminderType = reqJson.getInteger("reminderType");
        String reminderPhoneNumber = reqJson.getString("reminderPhoneNumber");
        String reminderPerson = reqJson.getString("reminderPerson");
        try {
            if (StrUtil.isEmptyIfStr(reminderPerson)){
                // 给操作人员发
                List<DsmsUser> userList = dsmsUserService.queryUserByDepartment(reminderDepartment);
                if (CollectionUtil.isNotEmpty(userList)) {
                    reminderPhoneNumber = userList.get(0).getMobileNo();
                    reminderPerson = userList.get(0).getUserName();
                }
            } else if(StrUtil.isEmptyIfStr(reminderPhoneNumber)){
                List<ReminderPerson> reminderPeople = reminderPersonMapper.selectList(new LambdaQueryWrapper<ReminderPerson>().in(ReminderPerson::getPersonName, reminderPerson));
                if (reminderPeople != null && !reminderPeople.isEmpty() && StringUtils.isNotBlank(reminderPeople.get(0).getPhone())) {
                    reminderPhoneNumber = reminderPeople.get(0).getPhone();
                }
            }
            // 调用工具类（仅传2个参数，极简使用）
//            String apiResponse = smsUtil.sendSmsByGet(reminderPhoneNumber, reminderContent);
            ReminderInfo reminderInfo = new ReminderInfo();
            reminderInfo.setReminderTitle(reminderTitle);
            reminderInfo.setReminderContent(reminderContent);
            reminderInfo.setReminderDepart(reminderDepartment);
            reminderInfo.setReminderType(reminderType);
//            reminderInfo.setOaUser(apiResponse);
            reminderInfo.setReminderPerson(reminderPerson);
            reminderInfo.setReminderPhoneNumber(reminderPhoneNumber);
            reminderInfo.setReminderTime(new Date());
            reminderInfo.setType(type);
            reminderInfoMapper.insert(reminderInfo);
            // 处理响应结果
//            System.out.println("接口响应结果：" + apiResponse);
            // 根据接口实际成功标识判断（示例：假设"success"为发送成功）
//            if ("success".equalsIgnoreCase(apiResponse.trim())) {
//                System.out.println("✅ 短信发送成功！");
//            } else {
//                System.out.println("❌ 短信发送失败，接口提示：" + apiResponse);
//            }

        } catch (IllegalArgumentException e) {
            // 处理参数错误（如手机号格式错、内容为空）
            System.err.println("参数异常：" + e.getMessage());
        } catch (Exception e) {
            // 处理网络/接口错误（如超时、响应码非200）
            System.err.println("网络/接口异常：" + e.getMessage());
        }
        return Answer.ok("发送成功");
    }

    @Override
    public Answer<Object> messageWarningTest(JSONObject reqJson) {
        String reminderContent = reqJson.getString("reminderContent");
        String reminderPhoneNumber = reqJson.getString("reminderPhoneNumber");
        String reminderUserName = reqJson.getString("reminderUserName");
        try {
            if(StrUtil.isEmptyIfStr(reminderPhoneNumber)){
                List<ReminderPerson> reminderPeople = reminderPersonMapper.selectList(new LambdaQueryWrapper<ReminderPerson>().in(ReminderPerson::getPersonName, reminderUserName));
                if (reminderPeople != null && !reminderPeople.isEmpty() && StringUtils.isNotBlank(reminderPeople.get(0).getPhone())) {
                    reminderPhoneNumber = reminderPeople.get(0).getPhone();

                }
            }
            // 调用工具类（仅传2个参数，极简使用）
            // 处理响应结果
//            System.out.println("接口响应结果：" + apiResponse);
            // 根据接口实际成功标识判断（示例：假设"success"为发送成功）
//            if ("success".equalsIgnoreCase(apiResponse.trim())) {
//                System.out.println("✅ 短信发送成功！");
//            } else {
//                System.out.println("❌ 短信发送失败，接口提示：" + apiResponse);
//            }

        } catch (IllegalArgumentException e) {
            // 处理参数错误（如手机号格式错、内容为空）
            System.err.println("参数异常：" + e.getMessage());
        } catch (Exception e) {
            // 处理网络/接口错误（如超时、响应码非200）
            System.err.println("网络/接口异常：" + e.getMessage());
        }
        return Answer.ok("发送成功");
    }



    private List<DeadlineNode> filiterNode(RectificationInfo rectificationInfo, List<DeadlineNode> deadlineNodeList) {
        if (CollectionUtil.isEmpty(deadlineNodeList)) {
            return deadlineNodeList;
        }
        // 排除 progress 为 / 的节点
        return deadlineNodeList.stream()
                .filter(node -> node.getProgress() == null || !"/".equals(node.getProgress()))
                .collect(Collectors.toList());
    }

}
